package com.fsd.core.wechat.entity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.fsd.core.util.SHA1;

import net.sf.json.JSONObject;

/**
 * 微信验证实体类
 */

public class WeChatShare {
	public static String appid = "wx2f299635cba53909";
    public static String secret = "478f055a834b3e7fcac1e4a0b689e402";

    public static String loadJson (String url) throws Exception{
        StringBuilder json = new StringBuilder();
        URL urlObject = new URL(url);
        URLConnection uc = urlObject.openConnection();
        uc.setConnectTimeout(30000);
        uc.setReadTimeout(30000);
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
        String inputLine = null;
        while ((inputLine = in.readLine()) != null) {
            json.append(inputLine);
        }
        in.close();
        return json.toString();
    }

    /**
     * 获取基础接口调用凭证
     * @return
     * @throws Exception
     */
    public static String getBaseToken() throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        String json = loadJson(url);
        JSONObject obj = JSONObject.fromObject(json);
        String token = obj.getString("access_token");
        return token;
    }

    /**
     * 获取JsApiTicket
     * @return
     * @throws Exception
     */
    public static String getjsapiTicket(String access_token) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
        String json = loadJson(url);
        JSONObject obj = JSONObject.fromObject(json);
        String jsapi_ticket = obj.getString("ticket");
        return jsapi_ticket;
    }

    public static Map<String, String> getWeChat(String url) throws Exception{
        Map<String, String> resultMap = new HashMap<String, String>();
        String accessToken = getBaseToken();
        String jsapi_ticket = getjsapiTicket(accessToken);
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
        //sha1加密
        String signature = SHA1.ToSha1(str);
        /*String imgUrl = url + "resource/zszt/skin/img/weixin300_300.jpg";*/
        resultMap.put("timestamp", timestamp);
        resultMap.put("noncestr", noncestr);
        resultMap.put("signature", signature);
        //resultMap.put("imgurl", imgUrl);
        resultMap.put("appid", appid);
        //最终获得调用微信js接口验证需要的三个参数noncestr、timestamp、signature
        return resultMap;
    }
}
